<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <span style="border-left: 6px solid #409eff; padding-left: 8px">常用联系人</span>
      </div>
      <el-input v-model="search" placeholder="搜索联系人" class="search-input"></el-input>
      <el-button type="primary" icon="el-icon-plus" @click="showAddDialog">新增联系人</el-button>
      <el-button
        v-if="ids.length > 0"
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete"
      >批量删除</el-button>
      <el-table
        :data="filteredContacts"
        :row-key="(row) => row.id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="contactName" label="姓名" align="center">
          <template slot-scope="scope">
            <span style="margin-right: 10px">{{ scope.row.contactName }}</span>
            <el-button
              size="small"
              v-if="!scope.row.defaultContact"
              @click="setAsDefault(scope.row)"
              class="default-contact-btn"
            >设为默认</el-button>
            <el-tag v-else>默认联系人</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contactPhone" label="电话" :formatter="filterPhone" align="center"></el-table-column>
        <el-table-column prop="contactEmail" label="邮箱" :formatter="filterEmail" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        :visible.sync="dialogVisible"
        title="新增/编辑联系人"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <el-form :model="newContact" :rules="rules" ref="newContact">
          <el-form-item label="姓名" prop="contactName">
            <el-input v-model="newContact.contactName"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="contactPhone">
            <el-input v-model="newContact.contactPhone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="contactEmail">
            <el-input v-model="newContact.contactEmail"></el-input>
          </el-form-item>
          <el-form-item label="设置默认联系人" prop="defaultContact">
            <el-switch v-model="newContact.defaultContact"></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savaC">确定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
  
<script>
export default {
  data() {
    return {
      dialogVisible: false, //弹框是否显示
      search: "", //搜索框
      contacts: [], //联系人列表
      ids: [],
      newContact: {
        contactName: "",
        contactPhone: "",
        contactEmail: "",
        defaultContact: "",
      },
      rules: {
        contactName: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        contactPhone: [
          { required: true, message: "请输入电话", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        contactEmail: [
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    filteredContacts() {
      return this.contacts.filter((contact) => {
        return (
          contact.contactName.indexOf(this.search) !== -1 ||
          contact.contactPhone.indexOf(this.search) !== -1 ||
          contact.contactEmail.indexOf(this.search) !== -1
        );
      });
    },
  },
  mounted() {
    this.getContacts();
  },
  methods: {
    //查询联系人列表
    async getContacts() {
      await this.$axios
        .post("/api/contacts/sel")
        .then((res) => {
          if (res.data.code === 1) {
            this.contacts = [...res.data.data];
          } else if (res.data.code === 0) {
          }
        })
        .catch((error) => {
          // 处理请求失败的错误
          if (error) {
            this.$message.error(error.response.data.msg);
          }
        });
    },
    //添加或编辑
    async savaC() {
      this.$refs.newContact.validate(async (valid) => {
        if (valid) {
          await this.$axios
            .post("/api/contacts/save", this.newContact)
            .then((res) => {
              if (res.data.code === 1) {
                this.getContacts();
                this.dialogVisible = false;
                this.$message({
                  type: "success",
                  message: res.data.msg,
                });
              } else if (res.data.code === 0) {
                this.$message({
                  type: "error",
                  message: res.data.msg,
                });
              }
            })
            .catch((error) => {
              // 处理请求失败的错误
              if (error) {
                this.$message.error(error.response.data.msg);
              }
            });
        } else {
          this.$message.error("请正确填写信息");
          return false;
        }
      });
    },
    //设置默认联系人·
    async setAsDefault(index) {
      await this.$axios
        .post("/api/contacts/udc/" + index.id)
        .then((res) => {
          if (res.data.code === 1) {
            this.getContacts();
            this.dialogVisible = false;
            this.$message({
              type: "success",
              message: res.data.msg,
            });
          } else if (res.data.code === 0) {
            this.$message({
              type: "error",
              message: res.data.msg,
            });
          }
        })
        .catch((error) => {
          // 处理请求失败的错误
          if (error) {
            this.$message.error(error.response.data.msg);
          }
        });
    },
    //批量删除联系人
    async delBatch() {
      let ids = {
        data: this.ids,
      };
      await this.$axios
        .delete("/api/contacts/del", ids)
        .then((res) => {
          if (res.data.code === 1) {
            this.getContacts();
            this.$message({
              type: "success",
              message: res.data.msg,
            });
          } else if (res.data.code === 0) {
            this.$message({
              type: "error",
              message: res.data.msg,
            });
          }
        })
        .catch((error) => {
          // 处理请求失败的错误
          if (error) {
            this.$message.error(error.response.data.msg);
          }
        });
    },
    //删除联系人
    async del(val) {
      let ids = {
        data: [val],
      };
      await this.$axios
        .delete("/api/contacts/del", ids)
        .then((res) => {
          if (res.data.code === 1) {
            this.getContacts();
            this.$message({
              type: "success",
              message: res.data.msg,
            });
          } else if (res.data.code === 0) {
            this.$message({
              type: "error",
              message: res.data.msg,
            });
          }
        })
        .catch((error) => {
          // 处理请求失败的错误
          if (error) {
            this.$message.error(error.response.data.msg);
          }
        });
    },
    //批量删除联系人
    handleBatchDelete() {
      this.$confirm("确认删除选中联系人吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delBatch();
        })
        .catch(() => {});
    },
    //删除联系人
    handleDelete(contact) {
      this.$confirm(`确认删除联系人 "${contact.contactName}" 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.del(contact.id);
        })
        .catch(() => {});
    },
    //批量选择
    handleSelectionChange(selectedContacts) {
      this.ids = selectedContacts.map((item) => item.id);
    },
    //显示编辑弹框
    showEditDialog(row) {
      this.newContact = Object.assign({}, row);
      this.dialogVisible = true;
    },
    //显示添加弹框
    showAddDialog() {
      this.newContact = {
        id: "",
        contactName: "",
        contactPhone: "",
        contactEmail: "",
        defaultContact: false,
      };
      this.dialogVisible = true;
    },
    // 过滤方法
    filterEmail(value) {
      const email = value.contactEmail;
      if (!email) return "";
      const [username, domain] = email.split("@");
      if (!username || !domain) return email;
      const filteredUsername =
        username.slice(0, 1) + "*".repeat(6) + domain.slice(-3);
      return `${filteredUsername}`;
    },
    filterPhone(value) {
      const phone = value.contactPhone;
      if (!phone) return "";
      const phoneNew = phone.slice(0, 3) + "*".repeat(6) + phone.slice(-2);
      return `${phoneNew}`;
    },
  },
};
</script>
  
<style scoped>
/* 卡片样式 */
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.search-input {
  width: 200px;
  margin-right: 10px;
}

/* 设为默认联系人 */
.default-contact-btn {
  display: none;
}
.el-table__row:hover .default-contact-btn {
  display: inline-block;
}
</style>